package com.wondersgroup.fjzlpt.yyzyzx.dao.impl.yyzygl.yysz;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.wondersgroup.fjzlpt.yyzyzx.util.ControllerUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.repository.sql.bean.page.PageQuerySQLBean;
import com.quick.framework.boot.repository.sql.bean.table.TableBean;
import com.quick.framework.boot.repository.sql.jdbcTemplate.impl.BaseJTDAOImpl;
import com.quick.framework.boot.repository.sql.jdbcTemplate.rs.ResultHandlerConstant;
import com.wondersgroup.fjzlpt.yyzyzx.dao.inter.yyzygl.yysz.HygzDao;

/**
 * 号源规则Dao
 * @author gzb   
 * 2017年8月10日
 */
@Repository
public class HygzDaoImpl extends BaseJTDAOImpl implements HygzDao{

	@Override
	@Autowired
	@Qualifier("TB_YYZY_HYGZ")
	public void setTb(TableBean tb) {
		super.setTb(tb);
	}

	/**
	 * 分页查询床位设置信息
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryPage(Map map) {
		ControllerUtils.pageFormat(map);
		JSONObject sqlObj = this.getQueryPageSql(map);
		
		List sqlParams = sqlObj.getJSONArray("sqlParams");
		PageQuerySQLBean pageBean = super.checkAndCreatePageQuerySQLBean(map, sqlObj.getString("sql"), "order by ZT,CJSJ desc", sqlParams.toArray());
		
		return super.queryPage(pageBean, ResultHandlerConstant.JSONARRAY);
	}
	
	/**
	 * 分页语句拼接
	 * @param map
	 * @return
	 */
	private JSONObject getQueryPageSql(Map<String,String> map){
		JSONObject result = new JSONObject();
		
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append("select a.*,c.JGS from ").append(this.tb.getTableName());
		sqlBuf.append(" a left join TB_ZD_YLJGXX b on a.PTJGID = b.PTJGID \n");
		sqlBuf.append("left join (select gzbh,count(PTJGID) JGS from TB_YYZY_JGKHGZ group by gzbh ) c on a.GZBH=c.GZBH ");
		sqlBuf.append("where 1=1 \n");
		List sqlParams = new ArrayList();
		
		//行政区划代码
		String value = map.get("XZQHDM");
		if(!StringUtils.isEmpty(value)){
			sqlBuf.append("and b.XZQHDM like ? ");
			sqlParams.add(value + "%");
		}
		//规则名称
		value = map.get("GZMC");
		if(!StringUtils.isEmpty(value)){
			sqlBuf.append("and a.GZMC like ? ");
			sqlParams.add("%" + value + "%");
		}
		//平台机构ID
		value = map.get("PTJGID");
		if(!StringUtils.isEmpty(value)){
			sqlBuf.append("and a.PTJGID = ? ");
			sqlParams.add(value);
		}
		
		result.put("sql", sqlBuf.toString());
		result.put("sqlParams", sqlParams);
		return result;
	}
}
